package com.baizhi.util;

import com.baizhi.dao.CmfzAdminDao;
import com.baizhi.dao.CmfzSuperAdmin;
import com.baizhi.entity.CmfzAdmin;
import com.baizhi.entity.Resource;
import com.baizhi.entity.SuperAdmin;
import com.baizhi.entity.UserRole;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Author: renpu
 * @Date: 2019/3/17 13:59
 * @Description:
 */


//Authorizing用户授权；
public class AuthorRealm extends AuthorizingRealm{

    /*@Autowired
    private CmfzAdminDao cmfzAdminDao;*/

    @Autowired
    private CmfzSuperAdmin cmfzSuperAdmin;


    //Authorization授权方法；
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

       //根据用户名称获取相应的身份；
        String userName =(String)principals.getPrimaryPrincipal();


        //调用方法从数据库进行查询；
        SuperAdmin superAdmin = cmfzSuperAdmin.selectByName(userName);

        if(userName.equals(superAdmin.getUserName())){
            //根据相应的用户名的id值就可以获取角色以及相应的操作；
            UserRole userRole = superAdmin.getUserRole();
            Resource resource = superAdmin.getResource();
            String roleName = userRole.getRoleName();
            String permission="article:add";
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            info.addRole(roleName);
            info.addStringPermission(permission);
            return info;
        }
        return null;
    }

    //Authentication认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //将用户输入得基本信息进行查询；
        String userName =(String)token.getPrincipal();

        System.out.println("认证方法"+"-------------登录用户的名称----------"+userName);

        SuperAdmin superAdmin = cmfzSuperAdmin.selectByName(userName);

        System.out.println("认证方法"+"-----------根据登录的用户名称去数据库查找------------"+superAdmin);

        //将用户输入的数据和数据库进行校验；
        if(userName.equals(superAdmin.getUserName())){

            //获取数据库用的相应信息，封装到Info里
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(superAdmin.getUserName(),superAdmin.getUserPassword(),this.getName());

            return info;
        }

        return null;
    }
}
